package com.basic.backend.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.basic.backend.common.BaseResponse;
import com.basic.backend.common.ErrorCode;
import com.basic.backend.common.ResultUtils;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.manager.CosManager;
import com.basic.backend.model.dto.file.UploadFileRequest;
import com.basic.backend.model.entity.User;
import com.basic.backend.model.enums.FileUploadBizEnum;
import com.basic.backend.service.UserService;
import com.qcloud.cos.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/file")
@Api(tags = "文件接口")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /**
     * 上传用户头像
     */
    @PostMapping("/upload-avatar")
    @ApiOperation(value = "上传头像")
    public BaseResponse<String> uploadAvatar(
            @RequestPart("file") MultipartFile file,
            HttpServletRequest request) {

        // 1. 获取登录用户
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null || loginUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }

        // 2. 校验文件
        validateAvatarFile(file);

        try {
            // 3. 生成存储路径
            String fileKey = generateAvatarKey(loginUser.getId(), file);

            // 4. 转换为临时文件
            File tempFile = convertToTempFile(file);

            // 5. 上传到COS（覆盖旧文件）
            PutObjectResult result = cosManager.putObject(fileKey, tempFile);

            // 6. 构建访问URL
            String avatarUrl = buildAccessUrl(fileKey);

            // 7. 更新用户信息
            updateUserAvatar(loginUser.getId(), avatarUrl);

            return ResultUtils.success(avatarUrl,"");
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件处理失败");
        }
    }

    //-- 辅助方法 --//

    /**
     * 生成头像存储路径
     */
    private String generateAvatarKey(Long userId, MultipartFile file) {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        return String.format("avatar/%d.%s", userId, suffix);
    }

    /**
     * 构建访问URL
     */
    private String buildAccessUrl(String fileKey) {
        return String.format("https://%s.cos.%s.myqcloud.com/%s",
                cosManager.getBucketName(),
                cosManager.getRegion(),
                fileKey);
    }

    /**
     * 头像文件校验
     */
    private void validateAvatarFile(MultipartFile file) {
        // 文件大小限制 2MB
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "头像大小不能超过2MB");
        }

        // 允许的图片类型
        String suffix = FileUtil.getSuffix(file.getOriginalFilename()).toLowerCase();
        List<String> allowedTypes = Arrays.asList("jpg", "jpeg", "png", "webp");
        if (!allowedTypes.contains(suffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "仅支持JPG/PNG/WEBP格式");
        }
    }

    /**
     * 转换为临时文件
     */
    private File convertToTempFile(MultipartFile file) throws IOException {
        String prefix = "avatar-tmp-" + System.currentTimeMillis();
        String suffix = "." + FileUtil.getSuffix(file.getOriginalFilename());
        File tempFile = File.createTempFile(prefix, suffix);
        file.transferTo(tempFile);
        return tempFile;
    }

    /**
     * 更新用户头像记录
     */
    private void updateUserAvatar(Long userId, String avatarUrl) {
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setUserAvatar(avatarUrl);

        boolean success = userService.updateById(updateUser);
        if (!success) {
            log.error("头像更新失败 userId: {}", userId);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "头像更新失败");
        }
    }


}